//
//  PurchaseViewController.m
//  iShop
//
//  Created by svp on 19/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PurchaseViewController.h"
#import "PurchaseProductCell.h"
#import "ResourceLoader.h"
#import "SubProduct.h"
#import "BaseProduct.h"
#import "ProductOrder.h"
#import "SBJson.h"
#import "NSManagedObjectExtenstion.h"
#import "Utils.h"
#import "ConstansDefine.h"
#import "OrderProductRequest.h"
#import "iShopAppDelegate.h"

@interface PurchaseViewController(Private)

-(void) keyboardDidShow:(NSNotification*)notification;
-(void) keyboardDidHide:(NSNotification*)notification;

@end

@implementation PurchaseViewController

@synthesize tableView = _tableView;
@synthesize changeModeButton = _changeModeButton;
@synthesize shop = _shop;
@synthesize product = _product;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void) viewDidLoad
{
	[super viewDidLoad];
	
	count = 1;
	UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditCell)];
	
	// For selecting cell.
	gestureRecognizer.cancelsTouchesInView = NO;
	
	[_tableView addGestureRecognizer:gestureRecognizer];
	
	[gestureRecognizer release];
	
	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		self.navigationItem.rightBarButtonItem.enabled = NO;
	}
}

-(void) endEditCell
{
	if (_keyboardHeight != 0) {
		[_tableView endEditing:YES];
		[self keyboardDidHide:nil];
	}
}

-(void) keyboardDidShow:(NSNotification*)notification
{
	NSLog(@"keyboardDidShow");
	if (_keyboardHeight != 0) {
		return;
	}
	NSDictionary* info = [notification userInfo];
	NSLog(@"notification:%@",info);
	NSLog(@"test%@",[_tableView indexPathForSelectedRow]);
	NSValue* aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
	_keyboardHeight = [aValue CGRectValue].size.height;
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height - _keyboardHeight + 44);
	[_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:_editCell] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
	
}

-(void) keyboardDidHide:(NSNotification *)notification
{
	NSLog(@"keyboardDidHide");
	if (_keyboardHeight == 0) {
		return;
	}
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height + _keyboardHeight -44);
	_keyboardHeight = 0;
}

-(void) viewWillAppear:(BOOL)animated
{
	NSLog(@"viewWillAppear");
	[super viewWillAppear:animated];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector (keyboardDidShow:)
												 name: UIKeyboardWillShowNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector (keyboardDidHide:)
												 name: UIKeyboardDidHideNotification object:nil];
	
	
}

-(void) viewWillDisappear:(BOOL)animated
{
	NSLog(@"viewWillDisappear");
	[super viewWillDisappear:animated];	
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dealloc {
	NSLog(@"CommentsViewController dealloc");
	[_tableView release];
    [super dealloc];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEditing]){
		return YES;
    }
	
    return NO;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return subProducts.count > 0?subProducts.count:1;
}

-(UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if ([tableView isEditing] && indexPath.row != count) {
		return UITableViewCellEditingStyleDelete;
	}
	return UITableViewCellEditingStyleInsert;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle

forRowAtIndexPath:(NSIndexPath *)indexPath

{
	
    if (editingStyle == UITableViewCellEditingStyleDelete)
		
    {		
        
		count --;
    } else if (editingStyle == UITableViewCellEditingStyleInsert)
		
    {
		
        count ++;
		
    }
	
	[tableView reloadData];
	
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	UIView *footView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)] autorelease];
	footView.backgroundColor = [UIColor grayColor];
	footView.alpha = 0.7;
	UILabel *totalText = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, [[NSString stringWithString:@"Total"] sizeWithFont:[UIFont systemFontOfSize:20]].width, 30)] autorelease];
	totalText.backgroundColor = [UIColor clearColor];
	totalText.text = @"Total";
	UILabel *totalValue = [[[UILabel alloc] initWithFrame:CGRectMake(10 + totalText.frame.size.width, 0, 320 - totalText.frame.size.width - 20, 30)] autorelease];
	totalValue.textAlignment = UITextAlignmentRight;
	totalValue.backgroundColor = [UIColor clearColor];
	totalValue.text = [NSString stringWithFormat:@"%.0f",total];
	[footView addSubview:totalText];
	[footView addSubview:totalValue];
	return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*) indexPath
{
	if (![tableView isEditing] || ([tableView isEditing] && indexPath.row != count)) {
		return 80;
	}
	return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{	
	if (![tableView isEditing] || ([tableView isEditing] && indexPath.row != count)) {
		
		PurchaseProductCell* cell = (PurchaseProductCell*)[tableView dequeueReusableCellWithIdentifier:@"PurchaseProductCell"];
		if (!cell) {
			NSLog(@"create cell");
			ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"PurchaseProductCell"] autorelease];
			cell = (PurchaseProductCell*)rc.resource;
			cell.delegate = self;
			if (subProducts.count > 0) {
				SubProduct *_subProduct = (SubProduct*)[subProducts objectAtIndex:indexPath.row];
				cell.productField.text = _subProduct.ColorAndSize;
				cell.maxAmount.text = [NSString stringWithFormat:@"(max:%d)",[_subProduct.Amount intValue]];
			}
			else {
				cell.productField.text = _product.BaseProduct.BaseName;
				cell.maxAmount.text = [NSString stringWithFormat:@"(max:%d)",[_product.Amount intValue]];
			}

			cell.amountField.text = [NSString stringWithFormat:@"%i",[[amountProducts objectAtIndex:indexPath.row] intValue]];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
		}
		
		return cell;
	}
	else if([tableView isEditing]){
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
		if (!cell) {
			NSLog(@"Create cell");
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"] autorelease];
		}
		cell.textLabel.text = @"More Product";
		return cell;
	}
	
	return nil;
}

-(IBAction) savePress:(id) sender;
{
	NSLog(@"savePress");
	[_tableView endEditing:YES];
	NSMutableArray *productOrders = [[NSMutableArray alloc] init];
	for ( int i=0; i<amountProducts.count && [[amountProducts objectAtIndex:i] intValue] > 0; i++) {
		ProductOrder *po = [NSEntityDescription insertNewObjectForEntityForName:@"ProductOrder" inManagedObjectContext:_shop.managedObjectContext];
		po.ProductID = _product.ProductID;
		po.Amount = [amountProducts objectAtIndex:i];
		po.ShopID = _shop.ShopID;
		if (subProducts.count == 0) {						
			po.SubProductID = nil;			
		}
		else {
			po.SubProductID = ((SubProduct*)[subProducts objectAtIndex:i]).SubProductID;
		}
		[productOrders addObject:po];
	}
	if (productOrders.count == 0) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"INFO" message:@"You do not order any product" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
		[alert show];
		[alert release];
		return;
	}
	NSMutableDictionary *test = [[NSMutableDictionary alloc] init];
	NSMutableArray *test1 = [[NSMutableArray alloc] init];
	for (ProductOrder *sp in productOrders) {
		[test1 addObject:[sp getJSONString]];
	}
	[test setObject:test1 forKey:@"ClientOrders"];
	[test setObject:[_product getPriceUnit] forKey:@"unitPrice"];
	[test setObject:[Utils getValueForRefKey:kSessionKey] forKey:KSessionKey];
	[((iShopAppDelegate*)[[UIApplication sharedApplication] delegate]) startSpinner:@"Waiting..."];
	OrderProductRequest *req = [[OrderProductRequest alloc] init];
	req.delegate = self;
	[req makeRequest:test];
	//[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(void) processRequestResult:(BOOL)result
{
	[((iShopAppDelegate*)[[UIApplication sharedApplication] delegate]) stopSpinner];
	if(result)
		[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(IBAction) cancelPress:(id) sender;
{
	NSLog(@"cancelPress");
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(IBAction) changeMode:(id) sender
{
	BOOL canEdit = [_tableView isEditing];
	canEdit = !canEdit;
	_tableView.editing = canEdit;
	_changeModeButton.style =  canEdit ? UIBarButtonItemStyleDone : UIBarButtonItemStyleBordered;
	[_tableView reloadData];
}

-(void) textFieldDidBeginEditing:(UITableViewCell*)cell
{
	_editCell = cell;
	[_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:_editCell] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
	
}

-(void) textFieldDidEndEditing:(UITableViewCell*)cell
{
	NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
	NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
	[f setNumberStyle:NSNumberFormatterDecimalStyle];
	if (((PurchaseProductCell*)cell).amountField.text.length == 0) {
		((PurchaseProductCell*)cell).amountField.text = @"0";
	}
	NSLog(@"test11:%@--%@",((PurchaseProductCell*)cell).amountField.text,(int)[f numberFromString:((PurchaseProductCell*)cell).amountField.text]);
	[amountProducts replaceObjectAtIndex:indexPath.row withObject:[f numberFromString:((PurchaseProductCell*)cell).amountField.text]];
	total = 0;
	for (NSNumber *x in amountProducts) {
		NSLog(@"test:%d",[x intValue]);
		total += [x longValue] * [_product.ProductUnitPrice longValue];
	}
	[_tableView reloadData];
}

-(void) prepareData
{
	total = 0;
	subProducts = [[_product.SubProducts allObjects] retain];
	int counts = -1;
	if (subProducts.count == 0) {
		counts = 1;
	}
	else {
		counts = subProducts.count;
	}

	amountProducts = [[NSMutableArray alloc] init];
	for (int i=0; i<counts; i++) {
		[amountProducts addObject:[NSNumber numberWithInt:0]];
	}
}
@end
